<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wh:rd01:rd01:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
      <DictLabel v-if="record.bred" :dictType="'wms_bred_status'" :dictValue="record.bred" />
    </template>
    <BasicForm @register="registerForm">
      <template #rds01List>
        <a-button
          v-if="!disabled"
          class="mb-2"
          @click="handleRds01Add"
          v-auth="'wh:rd01:rd01:edit'"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <a-button
          v-if="!disabled"
          class="mb-2 ml-2"
          @click="handleRds10Add"
          v-auth="'wh:rd01:rd01:edit'"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('参照入库任务明细') }}
        </a-button>
        <BasicTable @register="registerRds01Table" @row-click="handleRds01RowClick" >
          <template #summary>
            <TableSummary fixed>
              <TableSummaryRow>
                <TableSummaryCell :index="0" align="center"> 合计： </TableSummaryCell>
                <TableSummaryCell :index="1" :col-span="3"> </TableSummaryCell>
                <TableSummaryCell :index="5" align="center">
                  {{ iqty }}
                </TableSummaryCell>
                <TableSummaryCell :index="6" align="right">
                </TableSummaryCell>
                <!-- <TableSummaryCell :index="7" :col-span="4"> </TableSummaryCell> -->
              </TableSummaryRow>
            </TableSummary>
          </template>

        </BasicTable>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="flow_wh_rd01"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'wh:rd01:rd01:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
    <ListSelect
      ref="listSelectRef"
      :selectList="selectListRef"
      selectType="basInvSelect"
      :queryParams="queryParams"
      :checkbox="true"
      @select="handleSelect"
      v-show="false"
    />
    <ListSelect
      ref="listRd10SelectRef"
      :selectList="selectRd10ListRef"
      selectType="rd10Select"
      :queryParams="queryRd10Params"
      :checkbox="true"
      @select="handleRd10Select"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWhRd01Rd01Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Rd01, rd01Save, rd01Form } from '/@/api/wms/wh/rd01/rd01';
  import { BpmButton } from '/@/components/Bpm';
  import { companyTreeData } from '/@/api/sys/company';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { basPositionTreeData } from '/@/api/bas/pos/basPosition';
  import { ListSelect } from '/@/components/ListSelect';
  import { DictLabel } from '/@/components/Dict';
  import { TableSummary, TableSummaryCell, TableSummaryRow } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.rd01.rd01');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Rd01>({} as Rd01);
  const loadingRef = ref(false);
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);
  const whCode = ref<any>('');
  const disabled = ref<any>(false);
  const queryParams = ref({});

  const listRd10SelectRef = ref<any>(null);
  const selectRd10ListRef = ref<any>([]);
  const queryRd10Params = ref({});
  const userStore = useUserStore();


  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增采购入库') : t('编辑采购入库'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('所属公司'),
      field: 'companyCode',
      fieldLabel: 'company.companyName',
      component: 'TreeSelect',
      componentProps: {
        api: companyTreeData,
        allowClear: true,
        // disabled: computed(() => disabled.value),
        onChange: async (e) => {
          queryParams.value = {
            companyCode: e,
          };
          let obj = getFieldsValue()
          queryRd10Params.value = {
            'parent.companyCode': e,
            fstockid: obj.whCode,
            'parent.bred': obj.bred,
          };
          let arr = await rds01Table.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            await rds01Table.deleteTableDataRecord(item);
          });
        },
      },
      required: true,
    },
    {
      label: t('入库单号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFformat: 'YYYY-MM-DD',
      },
      dynamicDisabled: true,
    },
    {
      label: t('业务类型'),
      field: 'busType',
      component: 'Select',
      componentProps: {
        dictType: 'wh_rd01_bus_type',
        allowClear: true,
        disabled: computed(() => disabled.value),
      },
      required: true,
    },
    {
      label: t('红蓝标志'),
      field: 'bred',
      component: 'Select',
      componentProps: {
        dictType: 'wms_bred_status',
      },
      show: false,
    },
    {
      label: t('仓库'),
      field: 'whCode',
      fieldLabel: 'basWare.cwhname',
      component: 'TreeSelect',
      componentProps: {
        api: basWarehouseTreeData,
        allowClear: true,
        onChange:async (value) => {
          whCode.value = value  || '-1';
          setRds01Columns();
          let arr = await rds01Table.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            let editValueRefs = item.editValueRefs
            editValueRefs.posCode = ''
            await rds01Table.updateTableDataRecord(item.id, {
              ...item,
              posCode: '',
              // 'basPosition.posName': '',
              editValueRefs,
            });
          });
          let obj = getFieldsValue()
          queryRd10Params.value = {
            'parent.companyCode': obj.companyCode,
            fstockid: value,
            'parent.bred': obj.bred,
          };
        },
        // disabled: computed(() => disabled.value),
      },
      required: true,
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('修改人'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('数据来源'),
      field: 'sourceFlag',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      show:false
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        disabled: computed(() => disabled.value),
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('采购入库明细'),
      field: 'rds01List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rds01List',
      rules: [], // 明确设置为空数组，跳过表单验证
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue }] =
    useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerRds01Table, rds01Table] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRds01Delete.bind(this, record),
          },
          auth: 'wh:rd01:rd01:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
  });

  const iqty = computed(() => {
    let sumiqty = 0;
    for (const record of rds01Table.getDataSource()) {
      const {
        editValueRefs: { iqty },
      } = record;
      sumiqty += Number(iqty || 0);
    }
    return sumiqty;
  });


  async function setRds01Columns(_res: Recordable) {
    rds01Table.setColumns([
      // {
      //   title: t('来源ID'),
      //   dataIndex: 'sourceId',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('来源行ID'),
      //   dataIndex: 'sourceDid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      //   // ifShow: false,
      // },
      // {
      //   title: t('公司'),
      //   dataIndex: 'parent.company.companyName',
      //   width: 150,
      //   align: 'left',
      //   editRow: false,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: true,
      // },
      {
        title: t('商品编码'),
        dataIndex: 'basInv.viewCode',
        width: 140,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false, // 修改为 false，因为这是只读字段，不需要验证
      },
      {
        title: t('商品编码'),
        dataIndex: 'invCode',
        width: 140,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('商品名称'),
        dataIndex: 'basInv.invName',
        width: 160,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: false, // 修改为 false，因为这是只读字段，不需要验证
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.funitname',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: false, // 修改为 false，因为这是只读字段，不需要验证
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        // editRow: computed(() => !disabled.value),
        editComponent: 'InputNumber',
        editComponentProps: ({ record: record1 }) => {
          return {
            disabled: disabled.value,
            onChange: (value, label) => {
              let iqty = value;
              if (record.value.bred == 0) {
                if (value > 0) {
                  iqty = -value;
                }
              } else {
                if (value < 0) {
                  iqty = -value;
                }
              }
              // let weight = Number(record.cfree2 || 0);
              // let num = Number(value || 0);
              // let fweight = (num * weight).toFixed(4);
              rds01Table.updateTableDataRecord(record1.id, {
                ...record1,
                iqty,
              });
            },
          };
        },
        editRule: (value, _record) => {
          return new Promise((resolve, reject) => {
            if (value == 0) return reject('数量不能为0');
            if (!value || value == '') return reject('请输入数量');
            return resolve(undefined); // 验证成功
          });
        },
        showSummary: true,
        // editRule: true,
      },
      {
        title: t('货位名称'),
        dataIndex: 'posCode',
        dataLabel: 'basPosition.posName',
        width: 130,
        align: 'left',
        editRow: true,
        // editRow: computed(() => !disabled.value),
        editComponent: 'TreeSelect',
        editComponentProps: {
          disabled: disabled.value,
          api: basPositionTreeData,
          params: { whcode: whCode.value },
          allowClear: true,
          canSelectParent: false,
        },
        editRule: true,
      },
      {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 130,
        align: 'left',
        editRow: true,
        // editRow: computed(() => !disabled.value),
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('自由项2'),
        dataIndex: 'freeVO.cfree2',
        width: 130,
        align: 'left',
        // editRow: true,
        editRow: computed(() => !disabled.value),
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('自由项3'),
        dataIndex: 'freeVO.cfree3',
        width: 130,
        align: 'left',
        // editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          editRow: computed(() => !disabled.value),
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        // editRow: true,
        editRow: computed(() => !disabled.value),
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
  }

  async function setRds01TableData(_res: Recordable) {
    await setRds01Columns(_res);

    // 确保所有行都有唯一ID并处于可编辑状态
    const tableData = (record.value.rds01List || []).map((item: any, index: number) => ({
      ...item,
      id: item.id || new Date().getTime() + index,
      editable: true, // 强制设置为可编辑，确保验证回调被初始化
    }));

    rds01Table.setTableData(tableData);

    // 延迟确保所有行都正确进入编辑状态
    setTimeout(async () => {
      const dataSource = rds01Table.getDataSource();
      console.log('强制初始化所有行的编辑状态');
      for (const record of dataSource) {
        // 强制进入编辑状态，确保验证回调被初始化
        await record.onEdit?.(true, false);
        console.log(`行 ${record.id} 编辑状态:`, record.editable, 'validCbs:', record.validCbs?.length);
      }
    }, 500); // 增加延迟，确保表格完全渲染
  }

  function handleRds01RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  
  function handleRds10Add() {
    if (!getFieldsValue().companyCode) {
      showMessage('请先选择公司！');
      return;
    }
    if (!getFieldsValue().whCode) {
      showMessage('请先选择仓库！');
      return;
    }
    // let obj = getFieldsValue()
    // queryRd10Params.value = {
    //   companyCode: obj.companyCode,
    //   fstockid: obj.whCode,
    //   'parent.bred': obj.bred,
    // };
    console.log(queryRd10Params.value,'1111');
    
    selectRd10ListRef.value = [];
    listRd10SelectRef.value.openSelectModal();
  }

  function handleRds01Add() {
    if (!getFieldsValue().companyCode) {
      showMessage('请先选择公司！');
      return;
    }
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
    // rds01Table.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  

  function handleRd10Select(selectData) {
    selectData.forEach((item, index) => {
      rds01Table.insertTableDataRecord({
        id: new Date().getTime() + index,
        isNewRecord: true,
        editable: true,
        invCode: item.basInv.invCode,
        companyCode: item.parent.companyCode,
        basInv: {
          viewCode: item.basInv.viewCode,
          invName: item.basInv.invName,
          funitname: item.basInv.funitname,
        },
        parent: {
          company: {
            companyName: item.parent.companyName,
          },
        },
        iqty: item.syQty,
      });
    });
  }

  function handleSelect(selectData) {
    selectData.forEach((item, index) => {
      rds01Table.insertTableDataRecord({
        id: new Date().getTime() + index,
        isNewRecord: true,
        editable: true,
        invCode: item.invCode,
        companyCode: item.companyCode,
        basInv: {
          viewCode: item.viewCode,
          invName: item.invName,
          funitname: item.funitname,
          // weight: item.weight,
        },
        // cfree2: item.weight,
        parent: {
          company: {
            companyName: item.company.companyName,
          },
        },
      });
    });
  }

  function handleRds01Delete(record: Recordable) {
    rds01Table.deleteTableDataRecord(record);
  }

  async function getRds01List() {
    let rds01ListValid = true;
    let rds01List: Recordable[] = [];

    // 只验证当前数据源中的记录（未删除的记录）
    const dataSource = rds01Table.getDataSource();
    console.log('当前数据源:', dataSource);

    // 在验证前，强制确保所有行都进入编辑状态，这样验证回调才能被正确初始化
    console.log('验证前强制初始化所有行的编辑状态');
    for (const record of dataSource) {
      await record.onEdit?.(true, false);
      console.log(`行 ${record.id} 强制编辑状态:`, record.editable, 'validCbs:', record.validCbs?.length);
    }

    for (const record of dataSource) {
      console.log('验证记录:', record);

      try {
        // 确保记录处于可编辑状态，这样验证函数能正确访问当前值
        if (!record.editable) {
          await record.onEdit?.(true, false); // 先进入编辑状态
        }

        // 自定义验证逻辑，跳过有问题的嵌套字段验证
        let customValidResult = true;

        if (record.validCbs && Array.isArray(record.validCbs)) {
          console.log(`记录有 ${record.validCbs.length} 个验证函数`);

          const columns = rds01Table.getColumns();
          console.log('所有列信息:', columns.map((col: any, index: number) => ({
            index,
            title: col.title,
            dataIndex: col.dataIndex,
            editRule: col.editRule,
          })));

          // 不要跳过任何验证函数，直接按索引执行所有验证
          for (let i = 0; i < record.validCbs.length; i++) {
            try {
              const validResult = await record.validCbs[i]();
              const column = columns[i];
              console.log(`验证函数 ${i} (${column?.title || '未知'}) 结果:`, validResult);
              if (!validResult) {
                console.log(`验证函数 ${i} 失败，字段:`, column?.dataIndex);
                customValidResult = false;
              }
            } catch (validError) {
              const column = columns[i];
              console.log(`验证函数 ${i} (${column?.title || '未知'}) 异常:`, validError);
              customValidResult = false;
            }
          }
        }

        console.log('自定义验证结果:', customValidResult);

        if (!customValidResult) {
          console.log('记录验证失败:', record);
          rds01ListValid = false;
        }
      } catch (error) {
        console.log('记录验证异常:', error);
        rds01ListValid = false;
      }

      // 从 editValueRefs 中提取最新的编辑值
      const finalRecord = {
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      };

      // 详细调试 editValueRefs 的结构

      // 如果有 editValueRefs，将其中的值覆盖到最终记录中
      console.log('editValueRefs:', record.editValueRefs);
      if (record.editValueRefs) {
        Object.keys(record.editValueRefs).forEach(key => {
          const editValue = record.editValueRefs[key];
          console.log(`字段 ${key} 的编辑值:`, editValue);
          // 如果key 为 'freeVO,cfree1' 则 赋值成为 freeVO: { cfree1: editValue }
          if (key === 'freeVO,cfree1') {
            finalRecord['freeVO'] = { cfree1: editValue };
          }

          // 处理不同类型的编辑值
          if (editValue !== undefined && editValue !== null) {
            if (typeof editValue === 'object' && 'value' in editValue) {
              // Vue ref 对象
              finalRecord[key] = editValue.value;
            } else if (typeof editValue === 'object' && '_value' in editValue) {
              // 可能是另一种 ref 结构
              finalRecord[key] = editValue._value;
            } else {
              // 直接值
              finalRecord[key] = editValue;
            }
          }
        });

        // 特殊处理货位字段，可能存储在不同的地方
        const posCodeSources = [
          record.editValueRefs.posCode?.value,
          record.editValueRefs.posCode?._value,
          record.editValueRefs.posCode,
          record.posCode,
          record['basPosition.posCode'],
          record.basPosition?.posCode
        ];

        for (const posCodeValue of posCodeSources) {
          if (posCodeValue !== undefined && posCodeValue !== null && posCodeValue !== '') {
            finalRecord.posCode = posCodeValue;
            console.log('找到货位编码:', posCodeValue);
            break;
          }
        }
      }

      rds01List.push(finalRecord);
    }

    // 处理已删除的记录，但不进行验证
    for (const record of rds01Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rds01List.push({
        ...record,
        status: '1',
      });
    }

    console.log('最终验证结果:', rds01ListValid);
    if (!rds01ListValid) {
      throw { errorFields: [{ name: ['rds01List'] }] };
    }
    return rds01List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rd01Form(data);
    record.value = (res.rd01 || {}) as Rd01;
    record.value.__t = new Date().getTime();
    whCode.value = record.value.whCode || '-1';
    queryParams.value = {
      companyCode: record.value.companyCode,
    };
    // 如果是新增记录，设置默认公司代码
    if (record.value.isNewRecord && userStore.getProjecte?.code) {
      record.value.companyCode = userStore.getProjecte.code;
      record.value['company.companyName'] = userStore.getProjecte.name;
      queryParams.value = {
        companyCode: record.value.companyCode,
      };
    }
    queryRd10Params.value = {
      'parent.companyCode': record.value.companyCode,
      fstockid: record.value.whCode,
      'parent.bred': record.value.bred,
    };
    setFieldsValue(record.value);
    if (
      !record.value.status ||
      record.value.status == '9' ||
      record.value.status == '5' ||
      record.value.status == '6'
    ) {
      disabled.value = false;
    } else {
      disabled.value = true;
    }
    rds01Table.setProps({
      actionColumn: {
        ifShow: !disabled.value,
        width: 60,
        actions: (record: Recordable) => [
          {
            icon: 'i-ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleRds01Delete.bind(this, record),
            },
            auth: 'wh:rd01:rd01:edit',
          },
        ],
      },
    });
    await setRds01TableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'whCode',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'companyCode',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();

      // 在验证成功后再获取 rds01List 数据
      const rds01ListData = await getRds01List();
      data.rds01List = rds01ListData; // 确保数据中包含 rds01List

      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;

      const data = await validate(); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };

      // 在验证成功后再获取 rds01List 数据
      data.rds01List = await getRds01List();

      // console.log('submit', params, data, record);
      // console.log('submit', params, data, record);
      data.sourceId = record.value.sourceId;
      const res = await rd01Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
